<?php
/*
 * Copyright (c) 2023. ogg. Inc. All Rights Reserved.
 * ogg sit down and start building bugs in sunny weather.
 * Author: Tc <1224663799@qq.com>.
 * LastChangeTime: 2023-02-07 06:30:57
 * ChangeTime: 2023-04-26 10:21:34
 */

declare(strict_types=1);

namespace Hesb\LaravelPlus\Validate;


use Hesb\LaravelPlus\Exception\DtoValidationException;
use Hesb\LaravelPlus\Exception\InvalidArgumentException;
use Hesb\LaravelPlus\Scan\ValidationManager;
use Illuminate\Support\Facades\Validator;

class ValidationDto
{
    public function validate(string $className, $data): void
    {
        $this->validateResolved($className, $data);
    }

    private function validateResolved(string $className, $data): void
    {
        if (!is_array($data)) {
            throw new DtoValidationException('Class:' . $className . ' data must be object or array');
        }

        $validArr = ValidationManager::getData($className);
        if (empty($validArr)) {
            return;
        }
        ksort($validArr['rule']);



//        if(isset($validArr['rule']['file'])){
//            $validArr['rule']['file'] = "file|image";
//        }
//        $data['file'] = null;

//        echo "<pre>";
//        var_dump($data,$validArr);
//
//        echo "</pre>";

        $validator = Validator::make(
            $data,
            $validArr['rule'],
            $validArr['messages'] ?? [],
            $validArr['attributes'] ?? []);
        if ($validator->fails()) {
            //var_dump($validator->errors());
            throw new InvalidArgumentException(500, $validator->errors()->first());
        }

        // 递归校验判断
//        $notSimplePropertyArr = PropertyManager::getPropertyAndNotSimpleType($className);
//        foreach ($notSimplePropertyArr as $fieldName => $property) {
//            if (!empty($data[$fieldName])) {
////                if ($property->isClassArray()) {
////                    foreach ($data[$fieldName] as $item) {
////                        $this->validateResolved($property->arrClassName, $item);
////                    }
////                } elseif ($property->className != null) {
//                if ($property->className != null) {
//                    $this->validateResolved($property->className, $data);
//                }
//            }
//        }
    }
}
